<template>
	<view>
		<view class="layui-unselect layui-form-checkbox " @click="change(index)" :class="{'layui-form-checked':item.checked}"
		 v-for="(item,index) in list" :key="index" v-if="list.length > 0">
			<span>{{item.title}}</span>
			<i class="layui-icon layui-icon-ok"></i>
		</view>
		
		<input type="text" :value="curVal" :name="name" style="display: none;">
	</view>
</template>

<script>
	export default {
		name: "checkGroup",
		props: {
			name: {
				type: String,
				default: ''
			},
			list: {
				type: Array,
				default: function() {
					return [{}];
				}
			},
			values: {
				type: Array,
				default: function() {
					return [];
				}
			}
		},

		created() {
			this.curVal = this.values;
			for (var i = 0; i < this.list.length; i++) {
				var cur = this.list[i];
				cur['checked'] = this.isCheckedVal(cur.value) ;
			}
		},

		data() {
			return {
				curVal: []
			};
		},

		methods: {
			
			change: function(index) {
				var curValues = [] ;
				for (var i = 0; i < this.list.length; i++) {
					 var cur = this.list[i] ;
					 if (i == index) {
					 	cur.checked = !cur.checked ;
					 }
					 if (cur.checked) {
					 	curValues.push(cur.value);
					 }
				}
				this.curVal = curValues ;
				this.$emit("change", this.curVal);
			},
			
			isCheckedVal : function(value){
				if (this.curVal.length == 0) {
					return false ;
				}
				var arr = this.curVal ;
				for (var i = 0; i < arr.length; i++) {
					if (arr[i] == value) {
						return true ;
					}
				}
				return false ;
			}
		}
	}
</script>

<style>

</style>
